package com.bw.journal.list

import androidx.lifecycle.viewModelScope
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.module_journal.list.JournalIntent
import com.bawei.module_journal.list.JournalState
import com.bawei.module_journal.list.entity.RequestEntity
import com.bawei.module_journal.list.model.JournalListService

import com.bw.journal.list.entity.JournalListResponseEntity
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

class JournalListViewModel : BaseViewModel<JournalIntent>() {
    private val service:JournalListService by lazy{JournalListService()}
    private val _states = MutableStateFlow<JournalState>(JournalState.Init)//MutableStateFlow可变
    val states: StateFlow<JournalState>
        get() = _states

    fun loadJournal(it:JournalIntent.LoadJournalIntent){

        viewModelScope.launch {

            flow {
                val requestJournalList = service.requestJournalList(it.requestEntity)
                emit(requestJournalList)
            }.collect{
                _states.value = JournalState.LoadJournalSuccessState(it.datas)
            }
        }
    }

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                when(it){
                    is JournalIntent.LoadJournalIntent ->  loadJournal(it)//请求工作日志
                }
            }
        }
    }

}